package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectDate;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhander.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectDate> {

    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }



    @Override
    public void invoke(SubjectDate subjectDate, AnalysisContext analysisContext) {
        if (subjectDate == null){
            throw new GuliException(20001,"文件为空");
        }

        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectDate.getOneSubjectName());

        if (existOneSubject == null){
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectDate.getOneSubjectName());
            subjectService.save(existOneSubject);
        }

        String pid = existOneSubject.getId();
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectDate.getTwoSubjectName(), pid);
        if (existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectDate.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }

    }

    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSubject::getTitle,name);
        queryWrapper.eq(EduSubject::getParentId,"0");
        EduSubject oneSubject = subjectService.getOne(queryWrapper);
        return oneSubject;
    }

    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
        LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSubject::getTitle,name);
        queryWrapper.eq(EduSubject::getParentId,pid);
        EduSubject TneSubject = subjectService.getOne(queryWrapper);
        return TneSubject;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
